document.write(`<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport'>`);
document.write(`<link rel='stylesheet' type='text/css' href='../../YFree/css/YFree.css'>`);
document.write(`<script type='text/javascript' src='../../YFree/js/YFree_Extension.js'></script>`);

let native = true;
let DEBUG = true;
let version = "";
let IP = "";
let webName = "";
let yBundle;
let device = "";
let progress;
let oncreate;
let httpHeader;
let onyConfig = function () {
};

window.onload = function () {
    $(function () {
        yBundle = yFromJson(yRead(location.href.split("/")[location.href.split("/").length - 1]));
        native = yHasNative("getDebug");
        if (native) {
            IP = yCallNative("getIP");
            device = yCallNative("getDevice");
            version = yCallNative("getVersion");
            DEBUG = (yCallNative("getDebug") === "1");
            webName = yCallNative("getAppName");
            ySaveObj('yUserModel', yFromJson(yCallNative("getUserEntity")));
        } else onyConfig();
    });

    mui.ready(() => {
        mui.init({swipeBack: false});
        oncreate();
    });
};

function yCallNative(method, param = {}, callback = null) {
    if (callback) return bridge.call(`yPhone.${method}`, param, callback);
    else return bridge.call(`yPhone.${method}`, param);
}

function yHasNative(method) {
    return bridge.hasNativeMethod(`yPhone.${method}`) == 1;
}

function yOnConfig(onYConfig) {
    onyConfig = onYConfig;
}

function yOnCreate(onYCreate) {
    oncreate = onYCreate;
}

function yPost(jkid, params, onSuccess, onFail = null, showProgress = true, showErrorToast = true) {
    if (native) {
        if (device !== 'ios')
            yLog(jkid + ":request:" + (yIsEmpty(params) ? "无入参" : yToJson(params)));
        if (showProgress) yShowProgress();
        yCallNative('post', {IP: IP, jkid: jkid, params: params == null ? {} : params}, function (value) {
            if (showProgress) yDismissProgress();
            let result = yFromJson(value);
            switch (result.code) {
                case 1:
                    let response = yFromJson(result.result.trim());
                    yLog(jkid + ":responseSuccess:" + yToJson(response));
                    try {
                        let root = response.root;
                        if (root.code == 1) {
                            onSuccess(root.result);
                        } else {
                            if (showErrorToast) yToast(DEBUG ? "网络请求回执message：<br/>" + root.message : root.message);
                            if (onFail != null) onFail(root.code, root.message);
                        }
                    } catch (e) {
                        let msg = DEBUG ? "网络请求回执message解析异常，响应字符串：<br/>" + response : "网络请求错误，请重试";
                        if (showErrorToast) yToast(msg);
                        if (onFail != null) onFail("", msg);
                    }
                    break;
                case 0:
                    yLog(jkid + ":responseFailure:" + result.message);
                    if (showErrorToast) yToast(DEBUG ? "网络请求异常！！！<br/>ErrorNo:" + result.code + "<br/>Msg:" + result.message : "网络请求错误，请重试");
                    if (onFail != null) onFail(result.code, result.message);
                    break;
            }
        });
    } else {
        if (yIsEmpty(IP)) {
            //yToast("请正确配置YFree：IP");
            if (onFail != null) onFail(-999, "请正确配置YFree：IP");
            return null;
        }
        return $.ajax({
            method: 'POST',
            url: IP,
            data: {
                jkid: jkid,
                jkparam: yToJson(params)
            },
            headers: native ? yFromJson(yCallNative('getHttpHeader')) : httpHeader,
            timeout: 15000,
            cache: false,
            beforeSend: function (xhr) {
                yLog(jkid + ":request:" + (yIsEmpty(params) ? "无入参" : yToJson(params)));
                if (showProgress) yShowProgress();
            },
            success: function (response) {
                yLog(jkid + ":responseSuccess:" + yToJson(response));
                if (showProgress) yDismissProgress();
                if (response != "") {
                    try {
                        let root = response.root;
                        if (root.code == 1) {
                            onSuccess(root.result);
                        } else {
                            if (showErrorToast) yToast(DEBUG ? "网络请求回执message：<br/>" + root.message : root.message);
                            if (onFail != null) onFail(root.code, root.message);
                        }
                    } catch (e) {
                        let msg = DEBUG ? "网络请求回执message解析异常，响应字符串：<br/>" + response : "网络请求错误，请重试";
                        if (showErrorToast) yToast(msg);
                        if (onFail != null) onFail("", msg);
                    }
                } else {
                    if (showErrorToast) yToast(DEBUG ? "网络请求回执message解析异常，响应字符串：<br/>（空）" : "网络请求错误，请重试");
                    if (onFail != null) onFail("", "");
                }
            },
            error: function (error, textStatus, errorThrown) {
                let errorContent = textStatus + ":" + errorThrown;
                yLog(jkid + ":responseFailure:" + "网络请求异常！！！\tErrorNo:" + error.status + "\tMsg:" + errorContent);
                if (showProgress) yDismissProgress();
                if (showErrorToast) yToast(DEBUG ? "网络请求异常！！！<br/>ErrorNo:" + error.status + "<br/>Msg:" + errorContent : "网络请求错误，请重试");
                if (onFail != null) onFail(error.status.toString(), errorContent);
            }
        })
    }
}

function yInitScroll(wrapper = '.mui-scroll-wrapper') {
    mui(wrapper).scroll({
        scrollY: true, //是否竖向滚动
        scrollX: false, //是否横向滚动
        startX: 0, //初始化时滚动至x
        startY: 0, //初始化时滚动至y
        indicators: true, //是否显示滚动条
        deceleration: 0.0006, //阻尼系数,系数越小滑动越灵敏
        bounce: true //是否启用回弹
    });
}

function yCloseInput() {
    document.activeElement.blur();
}

function ySave(key, value) {
    localStorage.setItem(key, value);
}

function ySaveObj(key, obj) {
    localStorage.setItem(key, yToJson(obj));
}

function yRead(key) {
    return localStorage.getItem(key);
}

function yReadObj(key) {
    return yFromJson(localStorage.getItem(key));
}

function yDelete(key) {
    localStorage.removeItem(key);
}

function yIntent(page, params = null, type = 1) {
    if (params != null) {
        let dirs = page.split('/');
        ySave(dirs[dirs.length - 1], yToJson(params));
    }
    switch (type) {
        case 0: //替换
            location.replace(page);
            break;
        case 1: //前进
            //location.href = page;
            mui.openWindow({
                id: page,
                url: page
            });
            break;
        case 2: //新窗口
            window.open(page);
            break;
    }
}

function yRefresh() {
    location.reload(true);
}

function yFinishWithToast(content) {
    yToast(content);
    yRunOnDelay(500, () => {
        yFinish();
    });
}

function yFinish() {
    if (native) {
        yCallNative('close');
    } else {
        history.back();
    }
}

function yGetParam(key) {
    return YUrlParam.param(key);
}

function yRunOnDelay(delay, action) {
    return setTimeout(action, delay);
}

function yRunOnLoop(loopTime, action, firstDelay = false) {
    if (!firstDelay) action();
    return setInterval(action, loopTime);
}

function yStopRun(task) {
    clearTimeout(task);
    clearInterval(task);
}

function yIsEmpty(obj) {
    return obj == null || obj.toString() === "";
}

function yIsNotEmpty(obj) {
    return obj != null && obj.toString() !== "";
}

function yLog(msg) {
    if (native) {
        yCallNative('log', msg);
    } else {
        if (DEBUG) console.log(msg.toString());
    }
}

function yToast(msg) {
    if (native) {
        yCallNative('toast', msg);
    } else {
        // layer.open({
        //     content: msg,
        //     skin: 'msg',
        //     time: 2
        // });
        mui.toast(msg);
    }
}

function yShowProgress() {
    if (native) {
        yCallNative('showProgress');
    } else {
        progress = layer.open({
            type: 2,
            shadeClose: false,
            content: '拼命加载中，请稍后···'
        });
    }
}

function yDismissProgress() {
    if (native) {
        yCallNative('dismissProgress');
    } else {
        if (progress != null) {
            layer.close(progress);
            progress = null;
        }
    }
}

function yLShowBuilder(msg, btn, yes, no = null) {
    layer.open({
        content: msg,
        btn: btn,
        shadeClose: false,
        yes: function (index) {
            if (yes != null) yes(index);
        },
        no: function () {
            if (no != null) no();
        }
    });
}

function yShowBuilder(msg, btn, callback) {
    mui.confirm(msg, webName + '提示', btn, function (index) {
        callback(index);
    });
}

function yShowActionSheet(msg, btn, yes, no) {
    layer.open({
        content: msg,
        btn: btn.reverse(),
        skin: 'footer',
        shadeClose: false,
        yes: function (index) {
            if (no != null) no(index);
        },
        no: function () {
            if (yes != null) yes();
        }
    });
}

function yToJson(obj) {
    return JSON.stringify(obj);
}

function yFromJson(json) {
    return yIsEmpty(json) ? null : JSON.parse(json);
}

function yTemplate(container, templateID, params) {
    $(container).html(template(templateID, params));
}

function yTemplatePath(container, templatePath, params, onFinish) {
    $.get(templatePath, function (data) {
        let render = template.compile(data);
        let html = render(params);
        if (container != null) $(container).html(html);
        if (onFinish) onFinish(html);
    });
}

function yRandomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        default:
            return 0;
    }
}

function yAesEncrypt(content, password) {
    return String(CryptoJS.AES.encrypt(content, CryptoJS.SHA256(password), {
        iv: CryptoJS.enc.Hex.parse("0000000000000000"),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }));
}

function yAesDecrypt(content, password) {
    return CryptoJS.AES.decrypt(content.toString(), CryptoJS.SHA256(password), {
        iv: CryptoJS.enc.Hex.parse("0000000000000000"),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    }).toString(CryptoJS.enc.Utf8);
}

/* String */
String.prototype.contains = function (text) {
    return this.indexOf(text) >= 0;
};

String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
}

/* Array */
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

Array.prototype.contains = function (val) {
    return this.indexOf(val) > -1;
};

/* Date Format */
Date.prototype.format = function (fmt) { //author: meizz
    let o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/* Base64 */
function base64_encode(str) { // 编码，配合encodeURIComponent使用
    var c1, c2, c3;
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var i = 0, len = str.length, strin = '';
    while (i < len) {
        c1 = str.charCodeAt(i++) & 0xff;
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt((c1 & 0x3) << 4);
            strin += "==";
            break;
        }
        c2 = str.charCodeAt(i++);
        if (i == len) {
            strin += base64EncodeChars.charAt(c1 >> 2);
            strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            strin += base64EncodeChars.charAt((c2 & 0xF) << 2);
            strin += "=";
            break;
        }
        c3 = str.charCodeAt(i++);
        strin += base64EncodeChars.charAt(c1 >> 2);
        strin += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
        strin += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
        strin += base64EncodeChars.charAt(c3 & 0x3F)
    }
    return strin
};

function base64_decode(input) { // 解码，配合decodeURIComponent使用
    var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var output = "";
    var chr1, chr2, chr3;
    var enc1, enc2, enc3, enc4;
    var i = 0;
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
    while (i < input.length) {
        enc1 = base64EncodeChars.indexOf(input.charAt(i++));
        enc2 = base64EncodeChars.indexOf(input.charAt(i++));
        enc3 = base64EncodeChars.indexOf(input.charAt(i++));
        enc4 = base64EncodeChars.indexOf(input.charAt(i++));
        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;
        output = output + String.fromCharCode(chr1);
        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    }
    return utf8_decode(output);
};

function utf8_decode(utftext) { // utf-8解码
    var string = '';
    let i = 0;
    let c = 0;
    let c1 = 0;
    let c2 = 0;
    while (i < utftext.length) {
        c = utftext.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if ((c > 191) && (c < 224)) {
            c1 = utftext.charCodeAt(i + 1);
            string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
            i += 2;
        } else {
            c1 = utftext.charCodeAt(i + 1);
            c2 = utftext.charCodeAt(i + 2);
            string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
            i += 3;
        }
    }
    return string;
};

